package br.uefs.dexa.rfframework.gui.impl.alt;

import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.InvocationTargetException;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import br.uefs.dexa.rfframework.db.annotation.XMLImageCLEFAnnotationFormatter;
import br.uefs.dexa.rfframework.db.map.MapDatabaseManager;
import br.uefs.dexa.rfframework.gui.impl.DigitalImagePanel;
import br.uefs.dexa.rfframework.gui.interfaces.DigitalObjectPanel;
import br.uefs.dexa.rfframework.gui.interfaces.RFUserGUI;
import br.uefs.dexa.rfframework.gui.utils.ImagePanel;
import br.unicamp.ic.lis.rfframework.objects.IDigitalObject;

public class AltDigitalImagePanel extends DigitalObjectPanel {
	
private static final int DETAIL_BUTTON_HEIGTH = 20;
	
	
	public static final Color QUERY_SELECTION_COLOR = Color.GREEN;
	public static final Color RELEVANT_SELECTION_COLOR = Color.ORANGE;
	
	public static final int DEFAULT_VISUALIZATION_IMAGE_HEIGTH = 240;
	
	public static final int DEFAULT_QUERY_IMAGE_HEIGTH = 180;
	
	public static final int DEFAULT_RELEVANT_IMAGE_HEIGTH = 180;
	
	//vertical and horizontal gaps
	private static final int V_GAP = 5;
	private static final int H_GAP = 5;
	
	
	
	private ImagePanel imagePanel;
	private JPanel radioButtonsPanel;
	private JLabel detailButton;
	
	private JRadioButton yesButton;   
	private JRadioButton noButton;
	private JRadioButton notSureButton;
	private ButtonGroup group;
	
	private int imageHeigth; 
	private int panelHeigth; 
	
	
	
	
	public AltDigitalImagePanel(IDigitalObject object, int heigth) 
	{
		super(object, heigth);
		SwingUtilities.updateComponentTreeUI(this);
	}

	@Override
	protected void showObject(IDigitalObject object, int heigth) 
	{
		this.imageHeigth = heigth;
		
		setupComponents();
		setupPanel();
		addComponents();
		
		
	}
	
	private void setupComponents() 
	{

		try {
			
			if (!SwingUtilities.isEventDispatchThread()) {
			
				EventQueue.invokeAndWait(new Runnable() {
					public void run() 
					{
						createComponents();
						addDetailButtonListener();
						addRadioButtonListener();
					}
				});
				
			} else {
				createComponents();
				addDetailButtonListener();
				addRadioButtonListener();
			}
			
		} 	catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
	}
	
	private void createComponents()
	{
		imagePanel = new ImagePanel(getImagePath(), this.imageHeigth);
		radioButtonsPanel = new JPanel(new GridLayout(1, 0));
		radioButtonsPanel.setVisible(false);
		detailButton = new JLabel();
		detailButton.setSize(new Dimension(20, DETAIL_BUTTON_HEIGTH));		
		detailButton.setIcon(new ImageIcon(getClass().getResource("../../resources/search_30.png")));
		
		yesButton = new JRadioButton("Yes");
		noButton = new JRadioButton("No");
		notSureButton = new JRadioButton("Not sure");
		
		yesButton.putClientProperty("JComponent.sizeVariant", "large");
		noButton.putClientProperty("JComponent.sizeVariant", "large");
		notSureButton.putClientProperty("JComponent.sizeVariant", "large");
		
		group = new ButtonGroup();
		group.add(yesButton);
	    group.add(noButton);
	    group.add(notSureButton);
	    
	    radioButtonsPanel.add(yesButton);
	    radioButtonsPanel.add(noButton);
	    //radioButtonsPanel.add(notSureButton);
	    
	    SwingUtilities.updateComponentTreeUI(this);
	}
	
//	private void forceUpdate()
//	{
//		Container parent = this.getParent();
//	}
	
	
	private void addDetailButtonListener()
	{
		detailButton.addMouseListener(new MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				//detailButton.setBackground(Color.DARK_GRAY);
				showDetailDialog();
				
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				detailButton.setBorder(BorderFactory.createLineBorder(Color.BLACK));
				
			}

			@Override
			public void mouseExited(MouseEvent e) {
				detailButton.setBorder(BorderFactory.createEmptyBorder());
				
			}
			
		});
	}
	
	private void addRadioButtonListener()
	{
//		yesButton.addActionListener(new ActionListener(){
//		    public void actionPerformed(ActionEvent e) {
//		      // Do something here...
//		    	AltDigitalImagePanel.this.toogleSelected();
//		    	if(AltDigitalImagePanel.this.isSelected())
//		    		gui.addRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
//		    	else
//		    		gui.removeRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
//		    }
//		});
	}
	
	private void addComponents()
	{
		
		try {		
			if (!SwingUtilities.isEventDispatchThread()) {
			
				EventQueue.invokeAndWait(new Runnable() {
					public void run() 
					{
						add(detailButton);
						add(imagePanel);
						add(radioButtonsPanel);
					}
				});
				
			} else {
				add(detailButton);
				add(imagePanel);
				add(radioButtonsPanel);
			}
			
		} 	catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
			
	}
	
	
	private void setupPanel()
	{
		

		try {		
			if (!SwingUtilities.isEventDispatchThread()) {
			
				EventQueue.invokeAndWait(new Runnable() {
					public void run() 
					{
						setSize();
						setupLayout();
					}
				});
				
			} else {
				setSize();
				setupLayout();
			}
			
		} 	catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		

		
	}
	
	private void setSize()
	{
		//setBorder(BorderFactory.createLineBorder(Color.BLACK));
		int width = imagePanel.getWidth() + (2 * H_GAP);
		int heigth = imagePanel.getHeigth() + detailButton.getHeight() + radioButtonsPanel.getHeight() + (12 * V_GAP);
		setPreferredSize(new Dimension(width, heigth));
	}
	
	private void setupLayout()
	{
		FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
		//BoxLayout boxLayout = new BoxLayout(this, BoxLayout.PAGE_AXIS); 
		
		fl.setVgap(V_GAP);
		fl.setHgap(H_GAP);
		
		setLayout(fl);
		//setLayout(boxLayout);
	}
	
	@Override
	protected void setRelevantSelectionBehavior(RFUserGUI gui)
	{
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
//				addMouseListener(new java.awt.event.MouseAdapter() {
//				    public void mouseEntered(java.awt.event.MouseEvent evt) {
//				    	AltDigitalImagePanel.this.setBackground(RELEVANT_SELECTION_COLOR);
//				        
//				    }
//
//				    public void mouseExited(java.awt.event.MouseEvent evt) {
//				    	if(!AltDigitalImagePanel.this.isSelected())
//				    		AltDigitalImagePanel.this.setBackground(UIManager.getColor("control"));
//				    }
//				    
//				    public void mouseClicked(java.awt.event.MouseEvent evt) {
//
//				    	AltDigitalImagePanel.this.toogleSelected();
//				    	if(AltDigitalImagePanel.this.isSelected())
//				    		gui.addRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
//				    	else
//				    		gui.removeRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
//				    	
//				    }
//				});
				
				yesButton.addActionListener(new ActionListener(){
				    public void actionPerformed(ActionEvent e) {
				    	
						if (!AltDigitalImagePanel.this.isSelected()) {
							gui.addRelevantObject(AltDigitalImagePanel.this
									.getDigitalObject());
							AltDigitalImagePanel.this.setSelected(true);
						}
				    	
//				    	AltDigitalImagePanel.this.toogleSelected();
//				    	if(AltDigitalImagePanel.this.isSelected())
//				    		gui.addRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
//				    	else
//				    		gui.removeRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
				    }
				});
				
				noButton.addActionListener(new ActionListener(){
				    public void actionPerformed(ActionEvent e) {

						if (AltDigitalImagePanel.this.isSelected()) {
							gui.removeRelevantObject(AltDigitalImagePanel.this
									.getDigitalObject());
							AltDigitalImagePanel.this.setSelected(false);
						}
				    	
//				    	AltDigitalImagePanel.this.toogleSelected();
//				    	if(AltDigitalImagePanel.this.isSelected())
//				    		gui.addRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
//				    	else
//				    		gui.removeRelevantObject(AltDigitalImagePanel.this.getDigitalObject());
				    }
				});
				
				radioButtonsPanel.setVisible(true);
				AltDigitalImagePanel.this.revalidate();
				AltDigitalImagePanel.this.repaint();
			}
		});
		
	}
	
	@Override
	protected void setQuerySelectionBehavior(RFUserGUI gui)
	{
		SwingUtilities.invokeLater(new Runnable() {
			public void run() 
			{
				addMouseListener(new java.awt.event.MouseAdapter() {
				    public void mouseEntered(java.awt.event.MouseEvent evt) {
				    	AltDigitalImagePanel.this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
				    	//AltDigitalImagePanel.this.setBackground(QUERY_SELECTION_COLOR);
				        //DigitalImagePanel.this.setToolTipText("Add to Query");
				        
				    }

				    public void mouseExited(java.awt.event.MouseEvent evt) {
				    	if(!AltDigitalImagePanel.this.isSelected())
				    		AltDigitalImagePanel.this.setBorder(BorderFactory.createEmptyBorder());
				    		//AltDigitalImagePanel.this.setBackground(UIManager.getColor("control"));
				    }
				    
				    public void mouseClicked(java.awt.event.MouseEvent evt) {

				    	AltDigitalImagePanel.this.toogleSelected();
				    	if(AltDigitalImagePanel.this.isSelected())
				    		gui.addQueryObject(AltDigitalImagePanel.this.getDigitalObject());
				    	else
				    		gui.removeQueryObject(AltDigitalImagePanel.this.getDigitalObject());
				    }
				});
			}
		});
		
	}
	
	@Override
	protected void foolBehavior(RFUserGUI gui)
	{
		SwingUtilities.invokeLater(new Runnable() {
			public void run() 
			{
				addMouseListener(new java.awt.event.MouseAdapter() {
				    public void mouseEntered(java.awt.event.MouseEvent evt) {
				        AltDigitalImagePanel.this.setBackground(Color.RED);
				        //DigitalImagePanel.this.setToolTipText("Add to Query");
				        
				    }

				    public void mouseExited(java.awt.event.MouseEvent evt) {
				    	if(!AltDigitalImagePanel.this.isSelected())
				    		AltDigitalImagePanel.this.setBackground(UIManager.getColor("control"));
				    }
				    
				    public void mouseClicked(java.awt.event.MouseEvent evt) {

				    	AltDigitalImagePanel.this.toogleSelected();
				    	
				    }
				});
			}
		});
		
	}
	
	
	
	@Override
	protected void resetBehavior()
	{
		removeMouseListeners();
	}

	
	private void removeMouseListeners()
	{
		MouseListener[] ml = this.getMouseListeners();
		
		for (int i = 0; i < ml.length; i++) {
			
			MouseListener mouseListener = ml[i];
			
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					removeMouseListener(mouseListener);
				}
			});			
		}
	}
	
	private String getImagePath()
	{
		return MapDatabaseManager.getInstance().getImagePath(getObjectId());
	}
	
	private String getAnnotationPath()
	{
		return MapDatabaseManager.getInstance().getAnnotationPath(getObjectId());
	}
	
	
	private String getAnnotation()
	{
		//return MapDatabaseManager.getInstance().getAnnotation(getObjectId(), null);
		return MapDatabaseManager.getInstance().getAnnotation(getObjectId(), new XMLImageCLEFAnnotationFormatter());
	}
	
	
	
	private void showDetailDialog()
	{
		Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
		String imagePath = getImagePath();
		String annotation = getAnnotation();
		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() 
			{
				JDialog dialog = new JDialog(null, "", Dialog.ModalityType.DOCUMENT_MODAL);
		    	JPanel modalPanel = new JPanel();
		    	JEditorPane textArea = new JEditorPane("text/html", "");
		    	textArea.setText(annotation);
		    	textArea.setEditable(false);
		    	
		    	modalPanel.setLayout(new BoxLayout(modalPanel, BoxLayout.PAGE_AXIS));
		    	modalPanel.add(new ImagePanel(imagePath, DigitalImagePanel.MODAL_IMAGE_SCALE));
		    	modalPanel.add(textArea);
		    	
		    	dialog.setModal(true);
		    	dialog.add(modalPanel);
		    	dialog.pack();
		    	
		    	  
		    	dialog.setLocation((screen.width )/2 - dialog.getWidth()/2 , (screen.height)/2 - dialog.getHeight()/2);
		    	dialog.setVisible(true);
		    	dialog.dispose();
			}
		});
		
	}

}
